//
//  MyTradeViewController.m
//  1gene
//
//  Created by 1jiyin on 16/3/24.
//  Copyright © 2016年 1jiyin. All rights reserved.
//
//********我的订单********
#import "MyTradeViewController.h"
#import "TradeModel.h"
#import "HomeTrueTradeTraceViewController.h"
#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>




@interface MyTradeViewController ()<UIScrollViewDelegate,UnFinishedTableViewDelegate,GoingTableViewDelegate,FinishedTableViewDelegate>
@property(nonatomic,copy)UIScrollView *myScrollView;
@property(nonatomic,copy)UIView *view1;
@property(nonatomic,copy)UIView *view2;
@property(nonatomic,copy)UIView *view3;
@property(nonatomic,copy)UIButton *b1;//未完成
@property(nonatomic,copy)UIButton *b2;//进行中
@property(nonatomic,copy)UIButton *b3;//已完成
@property(nonatomic,copy)UIView *line;//下标识线
@property(nonatomic,copy)UIView *myView;

@property(nonatomic,copy)NSMutableArray *unfinishedArray;

@property(nonatomic,copy)NSMutableArray *goingArray;

@property(nonatomic,copy)NSMutableArray *finishedArray;

@property(nonatomic,copy)UnFinishedTableView *unFinishedTableView;

@property(nonatomic,copy)GoingTableView *goingTableView;

@property(nonatomic,copy)FinishedTableView *finishedTableView;

@end

@implementation MyTradeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:[UIView new]];
    [self initData];
    [self createNavigation];
    [self createUI];
    [self getAllItems];
    // Do any additional setup after loading the view.
}

-(void)initData
{
    _unfinishedArray=[NSMutableArray array];
    _goingArray=[NSMutableArray array];
    _finishedArray=[NSMutableArray array];
}

-(void)createUI2
{
    _myView=[[UIView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height-64)];
    _myView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:_myView];
    
    
    UILabel *lab=[[UILabel alloc]init];
    lab.bounds=CGRectMake(0, 0, 200, 30);
    lab.center=CGPointMake(self.view.center.x, self.view.center.y);
    lab.text=@"亲，你还没有任何订单哟!";
    lab.font=[UIFont systemFontOfSize:16];
    lab.textColor=[UIColor blackColor];
    lab.textAlignment=NSTextAlignmentCenter;
    //lab.backgroundColor=[UIColor grayColor];
    [_myView addSubview:lab];
    
    //未收到消息图片
    UIImageView *imgView=[[UIImageView alloc]initWithFrame:CGRectMake(lab.frame.origin.x+30, lab.frame.origin.y-155, 140, 155)];
    imgView.image=[UIImage imageNamed:@"receiveMessage_no"];
    [_myView addSubview:imgView];
    
}
-(void)createUI
{
    CGFloat btn_w=self.view.frame.size.width/7.0;
    CGFloat btn_h=30;
    _b1=[UIButton buttonWithType:UIButtonTypeCustom];
    _b1.tag=1;
    _b1.frame=CGRectMake(btn_w*1, 20+44+20, btn_w, btn_h);
    [_b1 setTitle:@"未完成" forState:UIControlStateNormal];
    [_b1 setTitleColor:[UIColor colorWithRed:232/255.0 green:151/255.0 blue:0 alpha:1] forState:UIControlStateNormal];
    _b1.titleLabel.font=[UIFont systemFontOfSize:15];
    [_b1 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_b1];
    
    _b2=[UIButton buttonWithType:UIButtonTypeCustom];
    _b2.tag=2;
    _b2.frame=CGRectMake(btn_w*3, 20+44+20, btn_w, btn_h);
    [_b2 setTitle:@"进行中" forState:UIControlStateNormal];
    [_b2 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    _b2.titleLabel.font=[UIFont systemFontOfSize:15];
    [_b2 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_b2];
    
    _b3=[UIButton buttonWithType:UIButtonTypeCustom];
    _b3.tag=3;
    _b3.frame=CGRectMake(btn_w*5, 20+44+20, btn_w, btn_h);
    [_b3 setTitle:@"已完成" forState:UIControlStateNormal];
    [_b3 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    _b3.titleLabel.font=[UIFont systemFontOfSize:15];
    [_b3 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_b3];
    
    _line=[[UIView alloc]initWithFrame:CGRectMake(_b1.frame.origin.x, CGRectGetMaxY(_b1.frame), btn_w, 1)];
    _line.backgroundColor=[UIColor colorWithRed:232/255.0 green:151/255.0 blue:0 alpha:1];
    [self.view addSubview:_line];
    
    //分割线
    UIView *selfLine=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_line.frame)+3, self.view.frame.size.width, 1)];
    selfLine.backgroundColor=[UIColor colorWithRed:235/255.0 green:235/255.0 blue:241/255.0 alpha:1];
    [self.view addSubview:selfLine];
    
    _myScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(selfLine.frame)+2, self.view.frame.size.width, self.view.frame.size.height-CGRectGetMaxY(selfLine.frame)-2)];
    _myScrollView.showsVerticalScrollIndicator=NO;
    _myScrollView.contentSize=CGSizeMake(self.view.frame.size.width*3, _myScrollView.frame.size.height);
    _myScrollView.pagingEnabled=YES;
    _myScrollView.delegate=self;
    _myScrollView.showsHorizontalScrollIndicator=NO;
    _myScrollView.bounces=NO;
    [self.view addSubview:_myScrollView];
    
    
    _view1=[[UIView alloc]initWithFrame:CGRectMake(0, 0, _myScrollView.frame.size.width, _myScrollView.frame.size.height)];
    _view1.backgroundColor=[UIColor redColor];
    [_myScrollView addSubview:_view1];
    
    
    
    _view2=[[UIView alloc]initWithFrame:CGRectMake(_myScrollView.frame.size.width, 0, _myScrollView.frame.size.width, _myScrollView.frame.size.height)];
    _view2.backgroundColor=[UIColor yellowColor];
    [_myScrollView addSubview:_view2];
    
    _view3=[[UIView alloc]initWithFrame:CGRectMake(_myScrollView.frame.size.width*2, 0, _myScrollView.frame.size.width, _myScrollView.frame.size.height)];
    _view3.backgroundColor=[UIColor grayColor];
    [_myScrollView addSubview:_view3];
    
    
    UnFinishedTableView *unFinishedTableView=[[UnFinishedTableView alloc]initWithFrame:_view1.bounds style:UITableViewStylePlain];
    [_view1 addSubview:unFinishedTableView];
    unFinishedTableView.myDelegate=self;
    _unFinishedTableView=unFinishedTableView;
    
    GoingTableView *goingTableView=[[GoingTableView alloc]initWithFrame:_view2.bounds style:UITableViewStylePlain];
    [_view2 addSubview:goingTableView];
    goingTableView.myDelegate=self;
    _goingTableView=goingTableView;
    
    FinishedTableView *finishedTableView=[[FinishedTableView alloc]initWithFrame:_view3.bounds style:UITableViewStylePlain];
    [_view3 addSubview:finishedTableView];
    finishedTableView.myDelegate=self;
    _finishedTableView=finishedTableView;

    
}




//unfinished的代理  未完成
-(void)gotoDetail:(NSString *)tradeId
{
   [self getTradeDetail:tradeId];
}
-(void)gotoPayMoney:(NSString *)tradeId
{
    [self getTradeDetail:tradeId];
}

//goingTableView的代理  进行中
-(void)gotoTradeDetail:(NSString *)tradeId
{
    HomeTrueTradeTraceViewController *vc=[HomeTrueTradeTraceViewController new];
    vc.tradeId=tradeId;
    [self.navigationController pushViewController:vc animated:YES];
}
//finishedTableView的代理  已完成
-(void)gotoOkTradeDetail:(NSString *)tradeId
{
    
}




-(void)btnClick:(UIButton *)sender
{
    [self changeLocation:sender.tag];
}


-(void)changeLocation:(NSInteger)index
{
    if (index==1) {
        _line.frame=CGRectMake(_b1.frame.origin.x, CGRectGetMaxY(_b1.frame), _b1.frame.size.width, 1);
        [_b1 setTitleColor:[UIColor colorWithRed:232/255.0 green:151/255.0 blue:0 alpha:1] forState:UIControlStateNormal];
        [_b2 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_b3 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    }else if(index==2){
        _line.frame=CGRectMake(_b2.frame.origin.x, CGRectGetMaxY(_b1.frame), _b1.frame.size.width, 1);
        [_b2 setTitleColor:[UIColor colorWithRed:232/255.0 green:151/255.0 blue:0 alpha:1] forState:UIControlStateNormal];
        [_b1 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_b3 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    }
    else if(index==3){
        _line.frame=CGRectMake(_b3.frame.origin.x, CGRectGetMaxY(_b1.frame), _b1.frame.size.width, 1);
        [_b3 setTitleColor:[UIColor colorWithRed:232/255.0 green:151/255.0 blue:0 alpha:1] forState:UIControlStateNormal];
        [_b1 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_b2 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    }
    _myScrollView.contentOffset=CGPointMake(self.view.frame.size.width*(index-1), 0);
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index=scrollView.contentOffset.x/_myScrollView.frame.size.width;
    index+=1;
    [self changeLocation:index];
}
-(void)createNavigation
{
    self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1];
    //返回
    UIButton *leftBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame=CGRectMake(0, 0, 25, 25);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"left_back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    
    //标题
    UILabel *title=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
    title.text=@"我的订单";
    title.font=[UIFont systemFontOfSize:22];
    title.textAlignment=NSTextAlignmentCenter;
    title.textColor=[UIColor whiteColor];
    self.navigationItem.titleView=title;
}
//返回上一页
-(void)leftBtnClick:(UIButton *)sender
{
    self.navigationController.navigationBar.hidden=YES;
    self.tabBarController.tabBar.hidden=NO;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//获取所有订单
-(void)getAllItems
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token=[user objectForKey:@"token"];

    [manager GET:[NSString stringWithFormat:GetAllItems,token] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        NSArray *arr=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"所有的订单======%@",arr);
        if (arr.count==0) {
            [self.view showTiShiMessage:@"亲,你还没有订单哟"];
        }
        for (NSDictionary *dic in arr) {
            NSInteger myId=[dic[@"is_paid"] integerValue];
            if (myId==0) {
                TradeModel *model=[[TradeModel alloc]initWithDictionary:dic];
                [_unfinishedArray addObject:model];
            }else if ([dic[@"is_complete"]integerValue]==0){
                TradeModel *model=[[TradeModel alloc]initWithDictionary:dic];
                [_goingArray addObject:model];
            }else if ([dic[@"is_complete"] integerValue]==1){
                TradeModel *model=[[TradeModel alloc]initWithDictionary:dic];
                [_finishedArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                _unFinishedTableView.dataArray=[NSMutableArray arrayWithArray:_unfinishedArray];
                _goingTableView.dataArray=[NSMutableArray arrayWithArray:_goingArray];
                _finishedTableView.dataArray=[NSMutableArray arrayWithArray:_finishedArray];
                
                [_unFinishedTableView reloadData];
                [_goingTableView reloadData];
                [_finishedTableView reloadData];
                
            });
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error%@",error.localizedDescription);
    }];
}

-(void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden=YES;
    self.navigationController.navigationBar.hidden=NO;
    [self.navigationController.navigationBar setTranslucent:YES];
    
}
//获取订单详情
-(void)getTradeDetail:(NSString *)tradeId
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token=[user objectForKey:@"token"];
    
    [self.view isLoading:YES];
    [manager GET:[NSString stringWithFormat:GetTradeDetail,token,tradeId] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.view isLoading:NO];
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"====%@",dic);
        if (dic) {
            [self startPayMoneyWithTradeNum:dic[@"order"][@"sn"] AndTradeTitle:dic[@"good"][@"name"] AndTradeDescription:dic[@"good"][@"short_discription"] AndMoney:dic[@"order"][@"final_price"]];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [self.view isLoading:NO];
        [self.view showTiShiMessage:@"程序员GG开了个小差"];
        NSLog(@"=====%@",error.localizedDescription);
        
    }];
}

-(void)startPayMoneyWithTradeNum:(NSString *)tradeNum AndTradeTitle:(NSString *)tradeTitle AndTradeDescription:(NSString *)tradeDescription AndMoney:(NSString *)money
{
    NSString *partner = @"2088121657755650";
    NSString *seller = @"2818614395@qq.com";
    NSString *privateKey = @"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIOdoCVrr/bWnmPE aDYoPJSH7cfrtGBTMFQjeE2v73GlTEWPjJNs7T6aTPcmXNeIiyLmLzOL8AgArrn2 pjgpw04nIetW3ZaiczrRzK3E+zadfEDf4KighWgGeYVgLRfNYirDBnaqQMk3XcvD hYoF6hTZWg4q8ABNcvXTI4FLGWtVAgMBAAECgYBdbCp7xWee55KAMK7kGkV+DMo8 iVN8uC/q2U6QnlxxJ6rvCUj4cG4qbK5LFID8QKC6gfdpOGCF3a4otCoiXYqSTxEU untEqS5rtovxvW/fP3TPLZ3DFFIwt2F7np6dvRQ5sLqRvHWNS4r716XDXfxV/Bsf lEwaaxAOZ4/6uG1nVQJBAMC28NxyRb/9MdrEufKDjMcuZEnw1TjSJVyuKlS8eSdT vq12viH+ZWeFHYcq9U8ZVN0vKEWUBmCHV8qZlyKS2RMCQQCu1j8cMG0bkQuB8WHt Nvs80lRXqIMvfsyDco06JjAdUJfULs187qwSrMN2nhwWQf+8gFSPv7YFfqcfAYHR F173AkEAqVxcwq9eYwJl3OfErr8zahx4II8ZI61zDkc1hnB4XLp5OULAh2llvps6 vv5exVvyu8tkrfkPvadT3QYrz0OUpwJBAK2kSV+01Ng5EQXId6rCHXoFpxC8YzYL qBCw94SWItkqjvCEXz/CR5Hwldy8IUcV22kax2FRVPVWGaMYuxawMHcCQGir3STI 2uP/RIcShyA12ZfwzYRbJqtAVt3C991l8piDrf5n0lxtSP1TeFZ/L5zjDjCGEveN a5HJuj4re8xhyps=";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([partner length]==0||[seller length]==0|| [privateKey length]==0) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"缺少partner或者seller或者私钥" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order=[[Order alloc]init];
    order.partner=partner;
    order.seller=seller;
    order.tradeNO=tradeNum;//订单ID(由商家自行定制)
    order.productName=tradeTitle;//商品标题
    order.productDescription=tradeDescription;//商品描述
    order.amount=[NSString stringWithFormat:@"%.2f",[money floatValue]];//商品价格
    order.notifyURL=@"http://www.1gene.com.cn";//回调URL
    
    
    order.service=  @"mobile.securitypay.pay";
    order.paymentType=@"1";
    order.inputCharset=@"utf-8";
    order.itBPay=@"30m";
    order.showUrl=@"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme=@"1gene";
    
    //将商品信息拼接成字符串
    NSString *orderSpec=[order description];
    NSLog(@"orderSpec=======%@",orderSpec);
    
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> singer=CreateRSADataSigner(privateKey);
    NSString *signedString=[singer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString=nil;
    if (signedString != nil) {
        orderString=[NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",orderSpec,signedString,@"RSA"];
        [[AlipaySDK defaultService]payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"返回的result=======%@",resultDic);
        }];
    }
    
}


-(void)viewWillDisappear:(BOOL)animated
{
    [self.navigationController.navigationBar setTranslucent:NO];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
